package com.oh.initializer;

import com.oh.handler.ProtocolClientHandler;
import com.oh.core.common.codec.OhDecoder;
import com.oh.core.common.codec.OhEncoder;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class ProtocolClientInitializer extends ChannelInitializer<SocketChannel> {
    private static final int MAX_FRAME_LENGTH = Integer.MAX_VALUE;  //最大长度
    private static final int LENGTH_FIELD_OFFSET = 5;  //长度偏移
    private static final int LENGTH_FIELD_LENGTH = 4;  //长度字段所占的字节数

    private static final int LENGTH_ADJUSTMENT = 0;
    private static final int INITIAL_BYTES_TO_STRIP = 0;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        //获取到pipeline
        ChannelPipeline pipeline = socketChannel.pipeline();
        //用户每次请求都会从第一个Handler开始
        //设置超时时间
        pipeline.addLast(new IdleStateHandler(0, 10, 0, TimeUnit.SECONDS));
        //解码器
//        pipeline.addLast("ProtocolDecoder",new PacketDecoder(MAX_FRAME_LENGTH,LENGTH_FIELD_OFFSET,LENGTH_FIELD_LENGTH,LENGTH_ADJUSTMENT,INITIAL_BYTES_TO_STRIP,false));
        pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, LENGTH_FIELD_OFFSET, 4, 0, 0));
        pipeline.addLast(new OhDecoder(Integer.MAX_VALUE, LENGTH_FIELD_OFFSET, 4, 0, 0, false));
        //编码器
        pipeline.addLast("ProtocolEncoder",new OhEncoder());
        //加入业务处理的handler
        pipeline.addLast("handler",new ProtocolClientHandler());
    }
}
